package com.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.base.BaseControllers;
import com.common.Criteria;
import com.model.XiaocaiArticle;
import com.model.XiaocaiUser;
import com.service.UserService;
import com.service.XiaocaiArticleService;
import com.service.XiaocaiUserService;
import com.util.SessionUtils;
import com.util.WebConstants;

@Controller
public class IndexController extends BaseControllers {

	@Resource
	private UserService userService;
	@Resource
	private XiaocaiUserService xiaocaiUserService;
	@Resource
	private XiaocaiArticleService xiaocaiArticleService;
	
	/**
	 * 用户登录提交表单
	 * 
	 * @param user
	 * @param authCode
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/login.json")
	public void login(XiaocaiUser xiaocaiUser, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		xiaocaiUser = xiaocaiUserService.login(xiaocaiUser);
		if (null != xiaocaiUser && xiaocaiUser.getId() > 0) {// 登录成功
			writerJson(response, successMsg("登录成功"));
			request.getSession().setAttribute(WebConstants.CURRENT_USER,
					xiaocaiUser);
		} else {// 登录失败
			writerJson(response, errorMsg("登录失败！用户名或密码输入错误！"));
		}
	}

	/**
	 * 打开网站首页
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/index")
	public ModelAndView index(ModelMap model) {
		Map<String, Object> context = new HashMap<String, Object>();
		return forword("index", context);
	}

	/**
	 * 打开用户登录页
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login")
	public ModelAndView login(ModelMap model, HttpServletRequest request) {
		Object userObject = request.getSession().getAttribute(
				WebConstants.CURRENT_USER);
		Map<String, Object> context = new HashMap<String, Object>();
		if (null == userObject) {
			return forword("login", context);
		} else {
			//return forword("user/index", context);
			return new ModelAndView("redirect:/user/index");
		}
	}

	/**
	 * 退出登录
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/logout")
	public void logout(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		request.getSession().setAttribute(WebConstants.CURRENT_USER, null);
		response.sendRedirect("/login");
	}

	@RequestMapping({ "/reg" })
	public ModelAndView reg() {
		Map<String, Object> context = new HashMap<String, Object>();
		context.put("referUserId", 0);
		return forword("reg", context);
	}
	@RequestMapping({"/reg/{referUserId}" })
	public ModelAndView referReg(@PathVariable int referUserId) {
		Map<String, Object> context = new HashMap<String, Object>();
		context.put("referUserId", referUserId);
		return forword("reg", context);
	}
	@RequestMapping(value = "/valiadteReg.json")
	@ResponseBody
	public void valiadteReg(HttpServletResponse response, int validateCode,
			String userEmail,String inputMoveUserName) {
		// 查找邮箱是否存在
		if (validateCode == 1) {
			XiaocaiUser xiaocaiUser = new XiaocaiUser();
			xiaocaiUser.setUserEmail(userEmail);
			boolean isExist = xiaocaiUserService
					.isExistByXiaocaiUser(xiaocaiUser);
			if (isExist)
				writerJson(response, errorMsg("已经存在"));
			else
				writerJson(response, successMsg("不存在"));
			return;
		}
		//积分转移查看用户是否存在
		if (validateCode == 2) {
			XiaocaiUser xiaocaiUser = new XiaocaiUser();
			xiaocaiUser.setUserEmail(inputMoveUserName);
			boolean isExist = xiaocaiUserService
					.isExistByXiaocaiUser(xiaocaiUser);
			if (isExist)
				writerJson(response, errorMsg("已经存在"));
			else
				writerJson(response, successMsg("不存在"));
			return;
		}
		// 查找其它
		/*System.out.println(userEmail);
		System.out.println(validateCode);*/

		writerJson(response, successMsg("删除成功"));
	}

	@RequestMapping(value = "/reg.json")
	@ResponseBody
	public void reg(String authCodeReg, XiaocaiUser xiaocaiUser,
			HttpServletRequest request, HttpServletResponse response) {
		// 验证码是否正确
		String vcode = SessionUtils.getValidateCode(request);
		if (null != vcode && !"".equals(vcode)) {
			// 清除验证码，确保验证码只能用一次
			SessionUtils.removeValidateCode(request);
			if (StringUtils.isBlank(authCodeReg)) {
				writerJson(response, errorMsg("验证码不能为空"));
				return;
			}
			// 判断验证码是否正确
			if (!(vcode.toLowerCase()).equals(authCodeReg)
					&& !authCodeReg.equals(vcode)) {
				writerJson(response, errorMsg("验证码输入错误"));
				return;
			}
		} else {
			writerJson(response, errorMsg("验证码已失效，请刷新验证码"));
			return;
		}
		boolean isExist = xiaocaiUserService.isExistByXiaocaiUser(xiaocaiUser);
		if (isExist){
			writerJson(response, errorMsg("已经存在此帐户名！"));
			return;
		}
		xiaocaiUser.setUserLevelName("普通会员");
		xiaocaiUser.setUserRegDate(new Date());
		xiaocaiUser = xiaocaiUserService.add(xiaocaiUser);
		if (null == xiaocaiUser) {
			writerJson(response, errorMsg("注册失败!"));
			return;
		} else {
			request.getSession().setAttribute(WebConstants.CURRENT_USER,
					xiaocaiUser);
			writerJson(response, successMsg("注册成功!"));
		}
	}

	@RequestMapping({"/article_list/{articleTypeId}/{articlePageStart}" })
	public ModelAndView articleList(@PathVariable int articleTypeId,@PathVariable int articlePageStart,Criteria criteria) {
		Map<String, Object> context = new HashMap<String, Object>();
		Map< String, Object> condition=new HashMap<String, Object>();
		condition.put("articleTypeIdP", articleTypeId);
		criteria.setCondition(condition);
		criteria.setPageSize(10);
		criteria.setPageStart((articlePageStart-1)*10);
		int total=xiaocaiArticleService.getTotal(criteria);
		List<XiaocaiArticle> list =xiaocaiArticleService.selectByCriteriaPagination(criteria);
		context.put("list", list);
		context.put("total", total);
		context.put("articlePageStart", articlePageStart);
		context.put("articleTypeIdP", articleTypeId);
		return forword("article_list", context);
	}
	
	
	
	
	@RequestMapping({"/article/{articleId}" })
	public ModelAndView article(@PathVariable int articleId) {
		Map<String, Object> context = new HashMap<String, Object>();
		XiaocaiArticle article=xiaocaiArticleService.selectByPrimaryKey(articleId);
		context.put("article",article);
		article.setArticleClickTimes(article.getArticleClickTimes()+1);
		xiaocaiArticleService.editXiaocaiArticle(article);
		return forword("article_info", context);
	}
	
}
